package com.then.component.login.ui.login;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.Observable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.luojilab.component.componentlib.router.ui.UIRouter;
import com.luojilab.componentservice.event.ResourceLoginCompletedEvent;
import com.luojilab.router.facade.annotation.Autowired;
import com.then.architecture.data.dto.Resource;
import com.then.basic.socket.SocketConfig;
import com.then.basic.socket.core.Registration;
import com.then.basic.socket.core.error.CommonError;
import com.then.basic.socket.data.CommClasses;
import com.then.component.login.LoginParams;
import com.then.component.login.R;
import com.luojilab.router.facade.annotation.RouteNode;
import com.then.component.login.dto.Login;
import com.then.component.login.ui.base.LoginModuleActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import javax.inject.Inject;

import timber.log.Timber;


@RouteNode(path = "/loginPage", desc = "登陆页面")
public class LoginActivity extends LoginModuleActivity<LoginDelegate> implements UMAuthListener {

    private static final int REQUEST_REGISTER_PHONE = 101;

    private static final int REQUEST_FORGOT_PASSWORD = 102;


    @Autowired
    String pwd;

    @Autowired
    String phoneNum;

    @Autowired
    String countryCode;


    @Inject
    UMShareAPI umShareAPI;

    private LoginActivityViewModel loginActivityViewModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        registEventbus();
        super.onCreate(savedInstanceState);
        loginActivityViewModel = ViewModelProviders.of(this, getViewModelFactory()).get(LoginActivityViewModel.class);

    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.setOnClickListener(this,
                R.id.login_btn_to_login,
                R.id.login_iv_wechat_way,
                R.id.login_btn_register,
                R.id.login_tv_forgot_pwd);
    }


    @Override
    protected Class getDelegateClass() {
        return LoginDelegate.class;
    }


    @Override
    public void actionViewModel(View view, Object o, int actionType) {
        int id = view.getId();

        if (id == R.id.login_btn_to_login) {
            String phoneNum = viewDelegate.getPhoneNum();
            String pwd = viewDelegate.getPwd();
            if (verification(phoneNum, pwd)) {
                login(viewDelegate.getPhoneNum(), viewDelegate.getPwd());
            }
        } else if (id == R.id.login_btn_register) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isRegister", true);
            UIRouter.getInstance().openUri(LoginActivity.this, "DDComp://login/registerPage", bundle, REQUEST_REGISTER_PHONE);
        } else if (id == R.id.login_tv_forgot_pwd) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isRegister", false);
            UIRouter.getInstance().openUri(LoginActivity.this, "DDComp://login/registerPage", bundle, REQUEST_FORGOT_PASSWORD);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommClasses.LoginLoginServerInfo info) {
        int status = info.success;
        if (status == 3) { // 数据库错误
//             viewDelegate.toast();
        }
        // 上报登录错误
        if (status != 0) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommonError.NetworkErrorInfo info) {
        if (info.errorType == CommonError.NetworkErrorInfo.ErrorType.ReadSocketDisconnected
                || info.errorType == CommonError.NetworkErrorInfo.ErrorType.ReadPackageFail
                || info.errorType == CommonError.NetworkErrorInfo.ErrorType.SendPackageFail) {

        } else if (info.errorType == CommonError.NetworkErrorInfo.ErrorType.ConnectServerFail
                || info.errorType == CommonError.NetworkErrorInfo.ErrorType.NetworkNotAvailable) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(CommClasses.LoginResourceServerInfo info) {
        if (info.success == 0) {
            Registration.getYetReg(SocketConfig.getResourceServer());
            //登录资源服务器成功，跳转至主界面
            startMainActivity();
        } else if (info.success == 1 || info.success == 2) { //1 key超时 ，2 key错误
            Log.d("AccountLoginActivity", "info.success:" + info.success);
        } else if (info.success == 3) { //其他错误

        } else if (info.success == 4) { //已经登录

        }
    }


    private void startMainActivity() {
        Bundle bundle = new Bundle();
        UIRouter.getInstance().openUri(LoginActivity.this, "DDComp://main/mainPage", bundle, REQUEST_FORGOT_PASSWORD);
    }


    /**
     * 验证用户名和密码
     *
     * @param phoneNum
     * @param pwd
     * @return
     */
    private boolean verification(String phoneNum, String pwd) {
        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调
        if (requestCode == REQUEST_REGISTER_PHONE || requestCode == REQUEST_FORGOT_PASSWORD) {
            if (resultCode == 1) {
                String phoneNum = data.getStringExtra("phoneNum");
                String pwd = data.getStringExtra("pwd");
                viewDelegate.setPhoneNum(phoneNum);
                viewDelegate.setPwd(pwd);
                login(phoneNum, pwd);
            }
        }
    }

    private void login(String phoneNum, String pwd) {
        LiveData<Resource<Login>> liveData = loginActivityViewModel.login(phoneNum, pwd);
        liveData.observe(LoginActivity.this, loginResource -> {
            Timber.d("userInfo:" + loginResource.data);
            if (loginResource.data != null) {
                loginActivityViewModel.startLogin(new LoginParams(9, loginResource.data.userInfo.bduss, phoneNum, "", "cn"));
            }
        });
    }


    @Override
    protected void onDestroy() {
        unRegistEventbus();
        super.onDestroy();
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            Timber.d("key:" + entry.getKey() + "value:" + entry.getValue());
        }
    }

    @Override
    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
        Timber.d("errorCode:" + i);
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media, int i) {

    }
}
